package com.cn.buffer;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

@Slf4j
public class ByteBufferDemo {

  @Test
  public void test1() {

    //ByteBuffer java nio 里面一个缓存队列，初始化是个写模式
    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

    // postion 是否还小于 limit
    log.info("hasRemaining -> {}", byteBuffer.hasRemaining());

    // postion 和 limit 的差值
    log.info("remaining -> {}", byteBuffer.remaining());

    byteBuffer.put("hello world".getBytes(StandardCharsets.UTF_8));

    //写模式 转化成 读模式，这样就可以读取了。
    byteBuffer.flip();

    ByteBuffer direct = ByteBuffer.allocateDirect(1024);
    direct.put(byteBuffer);

    //切换成 读模式
    direct.flip();

    int remaining1 = direct.remaining();
    log.info("remaining -> {}", remaining1);

    byte[] direct1 = new byte[remaining1];

    for (int i = 0; i < remaining1; i++)
      // get() 调用一次 position 指针移动一次
      direct1[i] = direct.get();
    log.info("direct -> {} {}", direct1, new String(direct1));

  }

}
